package com.example.sps.utils;

import com.aliyun.oss.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.net.openssl.ciphers.OpenSSLCipherConfigurationParser;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.nio.file.ReadOnlyFileSystemException;
import java.util.UUID;

/**
 * @ProjectName: Sps
 * @Titile: AliossUtils
 * @Author: nency
 * @Description: TODO
 */
@Data
@AllArgsConstructor
@Slf4j
public class AliossUtils {
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String bucketName;

    @SneakyThrows
//    public String upload(byte[] bytes,String objectName){
    public String upload(byte[] bytes, MultipartFile object){
        String originalFilename = object.getOriginalFilename();
        String extend = originalFilename.substring(originalFilename.lastIndexOf("."));
        String objectName = UUID.randomUUID().toString() + extend;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try{
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(bytes));
        }catch (OSSException oe){
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        }catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        StringBuffer stringBuffer = new StringBuffer("https://");
        stringBuffer
                .append(bucketName)
                .append(".")
                .append(endpoint)
                .append("/")
                .append(objectName);
        return stringBuffer.toString();
    }
}
